import Vue from 'vue';
import Vuex from 'vuex';
import Cookies from 'js-cookie';

import { initRoutes, resetRouter } from '@/router';
// import router from '@/store';
import { getAsyncRoutes } from '@/utils/tools';

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    asyncRoutes: [], // 后端传递的路由表
    routes: [] // 完整的路由表
  },

  mutations: {
    SET_ROUTES: (state, routes) => {
      state.asyncRoutes = routes;
      state.routes = initRoutes.concat(routes);
    },
    RESET_ROUTES: (state) => {
      state.asyncRoutes = [];
      state.routes = [];
    }
  },

  actions: {
    getRoutes({ commit }) {
      // 解析后端传递的路由表
      function parseRoutes(asyncRoutes) {
        let _newArr = [];
        asyncRoutes.forEach(item => {
          let _newItem = Object.assign({}, item);
          let _str = item.component;
          // 拼接
          // 注意import里面一定要使用模版语法
          _newItem.component = () => {
            return import(`@/views${_str}`);
          }
          // 坑点：如果webpack版本低，不支持import，就考虑require的写法
          // require的写法
          // _newItem.component = (resolve) => {
          //   return require([`@/views${_str}`], resolve);
          // }
          _newArr.push(_newItem);
        });
        return _newArr;
      }

      let _id = Cookies.get('id');

      if(_id) {
        return new Promise((resolve, reject) => {
          let _local = JSON.parse(localStorage.getItem('menu'));
          if(_local) {
            let _menu = parseRoutes(_local);
            commit('SET_ROUTES', _menu);
            resolve(_menu);
          } else {
            setTimeout(() => {
              let res = getAsyncRoutes(Number(_id));
  
              if(res.code !== 200) {
                reject(res.msg);
              }

              localStorage.setItem('menu', JSON.stringify(res.data));
  
              let _newArr = parseRoutes(res.data);
              commit('SET_ROUTES', _newArr);
              resolve(_newArr);
            }, 500);
          }
        })
      }

    },
    resetRoutes({ commit }) {
      resetRouter();
      commit('RESET_ROUTES');
    }
  }
}) 

export default store;